package afcp.alumni.action.base;

import java.util.Locale;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.ajax.JavaScriptResolution;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import afcp.alumni.model.URL;

public abstract class BaseAction implements ActionBean {

	protected MyActionBeanContext context;

	/**
	 * A Stripes action bean includes an {@link ActionBeanContext} object
	 * containing information related to the request and the context. this
	 * object is automatically set and may be accessed using this getter.
	 * 
	 * @return The Stripes {@link ActionBeanContext} object for this action
	 */
	@Override
	public MyActionBeanContext getContext() {
		return context;
	}

	/**
	 * This method is automatically called by Stripes to set the context
	 * property.
	 */
	@Override
	public void setContext(ActionBeanContext context) {
		this.context = (MyActionBeanContext) context;
	}

	public abstract String getUrl();

	/**
	 * Set the default view displayed on this page (this action) by returning a
	 * Stripes {@link Resolution} object. A basic implementation is
	 * <code>return this.toJsp();</code> (use this class method {@link #toJsp()}
	 * )
	 * 
	 * @return A Stripes {@link Resolution} object defining what is sent back to
	 *         the client for this request. You can use a
	 *         {@link ForwardResolution}, a {@link RedirectResolution}, a
	 *         {@link JavaScriptResolution}... Please refer to Stripes
	 *         documentations or Google for more examples.
	 */
	@DefaultHandler
	public abstract Resolution view();

	/**
	 * Returns a {@link RedirectResolution} object to this action. It means that
	 * the answer to this request is an HTTP redirection to this action. It may
	 * be used after sending a POST request to avoid refreshing problems. Be
	 * careful: with this redirection, some of the Stripes treatments can't be
	 * done, like checking the form and displaying error messages with the
	 * {@literal @}{@link Validate} annotation.<br/>
	 * This is a shorthand for
	 * <code>return new RedirectResolution(this.getClass());</code>
	 * 
	 * @return
	 */
	protected Resolution redirect() {
		return new RedirectResolution(this.getClass());
	}

	/**
	 * Shorthand for {@code getContext().forwardToString(url);}
	 * 
	 * @param url
	 *            to render
	 * @return the result rendered as a String
	 * @see {@link MyActionBeanContext#forwardToString(String)}
	 */
	public String forwardToString(String url) {
		return context.forwardToString(url);
	}
	
	public Message msgObj(String messageKey, Object... parameter) {
		return new LocalizableMessage(messageKey, parameter);
	}
	public String msgToStr(Message message) {
		return message.getMessage(context.getLocale());
	}
	public String msg(String messageKey, Object... parameter) {
		return new LocalizableMessage(messageKey, parameter).getMessage(context.getLocale());
	}
	public static String msg(Locale locale, String messageKey, Object... parameter) {
		return new LocalizableMessage(messageKey, parameter).getMessage(locale);
	}

	public static void addError(ValidationErrors errors, String messageKey, Object... parameter) {
		errors.addGlobalError(new LocalizableError(messageKey, parameter));
	}
	
	public void addFlashScope(String flashScopeKey, String messageKey, Object... parameter) {
		context.getMessages(flashScopeKey).add(new LocalizableMessage(messageKey, parameter));
	}
	public void addFlashScope(String flashScopeKey, Message message) {
		context.getMessages(flashScopeKey).add(message);
	}
	
//	@After
//	protected void setCurrentPage() {
//		this.context.setCurrentPage(this.getUrl());
//	}
	
	// if needed, get the previous URL :
	
//    public String getLastUrl() { 
//        HttpServletRequest req = getContext().getRequest(); 
//        StringBuilder sb = new StringBuilder(); 
//
//        // Start with the URI and the path 
//        String uri = (String) 
//            req.getAttribute("javax.servlet.forward.request_uri"); 
//        String path = (String) 
//            req.getAttribute("javax.servlet.forward.path_info"); 
//        if (uri == null) { 
//            uri = req.getRequestURI(); 
//            path = req.getPathInfo(); 
//        } 
//        sb.append(uri); 
//        if (path != null) { sb.append(path); } 
//
//        // Now the request parameters 
//        sb.append('?'); 
//        Map<String,String[]> map = 
//            new HashMap<String,String[]>(req.getParameterMap()); 
//
//        // Remove previous locale parameter, if present. 
//        map.remove(MyLocalePicker.LOCALE); 
//
//        // Append the parameters to the URL 
//        for (String key : map.keySet()) { 
//            String[] values = map.get(key); 
//            for (String value : values) { 
//                sb.append(key).append('=').append(value).append('&'); 
//            } 
//        } 
//        // Remove the last '&' 
//        sb.deleteCharAt(sb.length() - 1); 
//
//        return sb.toString(); 
//    }

	private URL currentUrl = null;
	public URL getCurrentUrl() {
		if (currentUrl == null) {
			currentUrl = new URL(getUrl(), context.getRequest().getQueryString());
		}
		return currentUrl;
	}

}
